import requests
import json
from sqlalchemy import create_engine

import time
import hmac
import hashlib
import base64
import urllib.parse
import pandas as pd

URL = 'https://oapi.dingtalk.com/robot/send?access_token=8d486ae88f342d07a6f677f52434efda8eb3932091a9fc81e42125d3150dda23'
SEC = "SECe1a904be6be4b7530987c5f38367de15964a7afaed5ce0fadddfd739ba5dc928"


def convertDfToMarkDown(df):
    markDowns = []
    for index, row in df.iterrows():
        mark = {}
        mark['title'] = row['fund_name'] + "(" + row['code'] + ":" + ")"
        mark['text'] = "### %s出现买点 \n  ![SKDJ](%s)\n " % (mark['title'], row['url'])
        markDowns.append(mark)
    return markDowns


def sendMarkDownMsg(url, sec, msg, title):
    # time.sleep(5000)
    url = url + "&timestamp=%s&sign=%s"
    headers = {"content-type": 'application/json'}
    timestamp = str(round(time.time() * 1000))
    secret = sec
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    url = url % (timestamp, sign)
    data = {}
    data['msgtype'] = "markdown"
    markdown = {}
    markdown["title"] = title
    markdown["text"] = msg
    data['markdown'] = markdown
    response = requests.post(url=url, data=json.dumps(data), headers=headers)
    return response;


def notify(ktype,conn,table_name,url,sec):
    if str(ktype)=='101':
        sql = "SELECT  DISTINCT buy.code,fund.fund_name FROM %s  as buy  LEFT JOIN shenge_money_fund_listed_open_ended_fund as fund ON buy.code = fund.fund_code  WHERE buy.ktype=%s  AND buy.flag='%s' " % (
        table_name, 101, time.strftime("%Y-%m-%d"))
        df1 = pd.read_sql(sql=sql, con=conn)
        df1['code'] = df1['code'].astype('int64')
        df1['code'] = df1['code'].astype('str')
        df1['url'] = "https://gitee.com/shenge08/python_spider/raw/master/tmp/" + df1['code'] + "日线" + "SKDJ.jpg"
        msgs = convertDfToMarkDown(df1)
        print(msgs)

        mark = {}
        mark['title'] = "wait wait"
        mark['text'] = "### %s分割 \n ###############  \n ########" % (time.strftime("%Y-%m-%d %H:%M:%S"))
        msgs.append(mark)

        for msg in msgs:
            time.sleep(4)
            aa = sendMarkDownMsg(url=url, sec=sec, title=msg['title'], msg=msg['text'])
            print(aa.text)


def connect_db():
    connect_info = 'mysql+pymysql://paqi:chs518518!@rm-bp1v9plylv4340as7qo.mysql.rds.aliyuncs.com:3306/paqi?charset=utf8'
    engine = create_engine(connect_info)
    return engine

conn =connect_db()
notify(101,conn,"shenge_money_buy_point_tmp",URL,SEC)